package wty;

import org.json.JSONObject;
import wty.Bee.User;
import wty.Bee.UserDao;
import org.mindrot.jbcrypt.BCrypt; // 确保导入 BCrypt

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/wty/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            System.out.println("我进来登录了");
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");

            // 1. 读取请求体
            StringBuilder sb = new StringBuilder();
            try (BufferedReader reader = request.getReader()) {
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            }
            String requestBody = sb.toString();
            System.out.println("请求体数据: " + requestBody);

            // 2. 解析 JSON
            JSONObject json = new JSONObject(requestBody);
            String username = json.getString("username");
            String password = json.getString("userpasswd");
            System.out.println("解析后的数据: " + username + ", " + password);

            // 数据库对比
            String userId = validateUser(username, password);

            if (userId != null) {
                //存入session状态
                HttpSession session = request.getSession();
                session.setAttribute("userId", userId);

                JSONObject responseJson = new JSONObject()
                        .put("success", true)
                        .put("userId", userId)
                        .put("msg", "登录成功");

                response.getWriter().print(responseJson);
            } else {
                HttpSession session = request.getSession();
                session.setAttribute("userId", null);

                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
                JSONObject responseJson = new JSONObject()
                        .put("success", false)
                        .put("msg", "用户名或密码错误");

                response.getWriter().print(responseJson);
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            try {
                response.getWriter().print(
                        new JSONObject()
                                .put("status", "error")
                                .put("message", e.getMessage())
                );
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("正在使用get方法处理请求，建议不要这样做！");
        doPost(request, response);
    }


    //使用 BCrypt.checkpw() 验证密码哈希
    private String validateUser(String username, String password) {
        UserDao userDao = new UserDao();
        User user = userDao.selectByUsername(username);

        // 用户存在且密码匹配时返回用户ID
        if (user != null && BCrypt.checkpw(password, user.getPassword())) {
            return user.getUserid();
        }
        return null; // 验证失败
    }
}